<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>警告管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索 -->
    <el-form :inline="true" style="margin-top: 20px;">
      <el-form-item>
        <el-button size="small" @click="exportExcel">导出Excel</el-button>
      </el-form-item>
      <el-form-item>
        <el-input
          size="small"
          v-model="stationName"
          placeholder="请输入充电桩名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          size="small"
          v-model="reason"
          placeholder="请输入警告描述"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          size="small"
          v-model="userName"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select size="small" v-model="status" placeholder="请选择处理状态">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          size="small"
          v-model="startTime"
          align="right"
          type="date"
          placeholder="选择警告时间（年/月/日）"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="chongzhi"
          >重置</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="openWarn()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table
      size="small"
      ref="multipleTable"
      :data="warnData"
      element-loading-text="拼命加载中"
      style="width: 100%;"
      v-horizontal-scroll
    >
      <el-table-column
        align="center"
        sortable
        type="index"
        label="序号"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="siteName"
        label="站点名称"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="factoryType"
        :formatter="formatFactoryType"
        label="充电桩厂家类型"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="stationName"
        label="充电桩名称"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="stationPortName"
        label="端口名称"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="userName"
        label="用户名"
        width="140"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="reason"
        label="警告描述"
        width="200"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="phone"
        label="手机号"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="status"
        :formatter="Status"
        label="处理状态"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="type"
        :formatter="Type"
        label="类型"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="time"
        label="警告时间"
        width="150"
      >
        <template slot-scope="scope">
          <div>{{ transformDate(scope.row.time) }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="openWarn(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="deleWarn(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑界面 -->
    <el-dialog :title="tit" :visible.sync="editFormVisiible" width="40%">
      <el-form label-width="100px">
        <!-- <el-form-item label="站点Id" prop="siteId">
          <el-input size="small" v-model="siteId" auto-complete="off" placeholder="请输入站点Id"></el-input>
        </el-form-item> -->
        <el-form-item label="充电桩名称" prop="stationId">
          <el-select v-model="stationId" placeholder="请选择充电桩名称">
            <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <!-- <el-input size="small" v-model="stationId" auto-complete="off"
            placeholder="请输入充电桩Id(不知道id的话可以去电桩管理列表里面查看)"></el-input> -->
        </el-form-item>
        <!-- <el-form-item label="端口Id" prop="portId">
          <el-input size="small" v-model="portId" auto-complete="off" placeholder="请输入端口Id"></el-input>
        </el-form-item> -->
        <el-form-item label="警告描述" prop="reasons">
          <el-input
            size="small"
            v-model="reasons"
            auto-complete="off"
            placeholder="请输入警告描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="statuss" placeholder="请选择处理状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="警告时间" prop="duration">
          <el-date-picker
            v-model="time"
            size="small"
            type="datetime"
            placeholder="请选择警告时间"
            align="right"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="type" placeholder="请选择警告类型">
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog()">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="addWarn()"
          v-if="tit == '添加'"
          >添加</el-button
        >
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="upWarn()"
          v-if="tit == '修改'"
          >修改</el-button
        >
      </div>
    </el-dialog>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
  </div>
</template>

<script>
import {
  getWarnList,
  addWarn,
  deleteWarn,
  upWarn,
  getStationAdminList,
  getAdminStationPortListHttp
} from "../../api/userMG";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import Pagination from "../../components/Pagination";
export default {
  data() {
    return {
      warnData: [],
      loading: false,
      stationName: "",
      reason: "",
      userName: "",
      status: "",
      startTime: "",
      timestamp: "",
      options: [
        {
          value: 0,
          label: "未处理"
        },
        {
          value: 1,
          label: "已处理"
        }
      ],
      editFormVisiible: false,
      tit: "添加",
      siteId: "",
      stationId: "",
      portId: "",
      reasons: "",
      statuss: "",
      type: "",
      time: "",
      options1: [
        {
          value: 0,
          label: "用户创建"
        },
        {
          value: 1,
          label: "桩主创建"
        },
        {
          value: 2,
          label: "充电桩自主上传"
        }
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      options3: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 20,
        total: 10
      }
    };
  },
  // 注册组件
  components: {
    Pagination
  },
  created() {
    this.getdata(Number(localStorage.getItem("warnPage")) || 1);
    this.gteElectricPile();
  },
  methods: {
    // 分页插件事件
    callFather(parm) {
      this.pageparm.page = parm.currentPage;
      this.getdata(parm.currentPage);
    },
    exportExcel() {
      var parameter = {
        page: -2,
        stationName: this.stationName,
        reason: this.reason,
        userName: this.userName,
        status: this.status,
        startTime: this.timestamp
      };
      getWarnList(parameter).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          this.warnData = res.data.list;
          return;
        }
      });
      setTimeout(() => {
        //转换成excel时，使用原始的格式
        var xlsxParam = { raw: true };
        let fix = document.querySelector(".el-table__fixed-right");
        let wb;
        //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
        if (fix) {
          wb = XLSX.utils.table_to_book(
            this.$refs.multipleTable.$el.removeChild(fix),
            xlsxParam
          );
          this.$refs.multipleTable.$el.appendChild(fix);
        } else {
          wb = XLSX.utils.table_to_book(
            this.$refs.multipleTable.$el,
            xlsxParam
          );
        }
        var wbout = XLSX.write(wb, {
          bookType: "xls",
          bookSST: true,
          type: "array"
        });
        try {
          // 如果是IE浏览器，使用Blob通过navigator.msSaveBlob保存
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(
              new Blob([wbout], { type: "application/octet-stream" }),
              "警告列表.xlsx"
            );
          } else {
            // 在其他浏览器中使用file-saver保存文件
            saveAs(
              new Blob([wbout], { type: "application/octet-stream" }),
              "警告列表.xlsx"
            );
          }
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      }, 1000);
      setTimeout(() => {
        this.getdata(1);
      }, 2000);
    },
    // 获取充电桩列表
    gteElectricPile() {
      getStationAdminList().then(res => {
      // getAdminStationPortListHttp().then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          res.data.list.forEach(item => {
            this.options3.push({ label: item.stationName, value: item.id });
          });
          return;
        }
      });
    },
    // 修改
    upWarn() {
      (this.loading = true),
        upWarn({
          id: this.id,
          stationId: this.stationId,
          reason: this.reasons,
          status: this.statuss,
          time: Math.floor(new Date(this.time).getTime() / 1000),
          type: this.type,
          createTime: this.createTime
        }).then(res => {
          this.loading = false;
          if (res.code == 200) {
            this.editFormVisiible = false;
            this.$message.success(res.msg);
            localStorage.setItem("warnPage", this.pageparm.currentPage);
            location.reload();
          } else {
            this.editFormVisiible = false;
            this.$message.error(res.msg);
          }
        });
    },
    // 添加
    addWarn() {
      (this.loading = true),
        addWarn({
          stationId: this.stationId,
          reason: this.reasons,
          status: this.statuss,
          time: Math.floor(new Date(this.time).getTime() / 1000),
          type: this.type,
          createTime: ""
        }).then(res => {
          this.loading = false;
          if (res.code == 200) {
            this.editFormVisiible = false;
            this.$message.success(res.msg);
            localStorage.setItem("warnPage", 1);
            location.reload();
          } else {
            this.editFormVisiible = false;
            this.$message.error(res.msg);
          }
        });
    },
    // 关闭编辑对话框
    closeDialog() {
      this.editFormVisiible = false;
      this.$message({
        type: "info",
        message: "已取消编辑"
      });
    },
    // 打开编辑器
    openWarn(row) {
      this.editFormVisiible = true;
      if (row != undefined && row != "undefined") {
        this.tit = "修改";
        this.id = row.id;
        this.siteId = row.siteId;
        this.stationId = row.stationId;
        this.portId = row.portId;
        this.reasons = row.reason;
        this.statuss = row.status;
        this.time = new Date(row.time * 1000);
        this.type = row.type;
        this.createTime = row.createTime;
      } else {
        this.tit = "添加";
        this.siteId = "";
        this.stationId = "";
        this.portId = "";
        this.reasons = "";
        this.statuss = "";
        this.time = "";
        this.type = "";
      }
      return;
      var userdata = JSON.parse(localStorage.getItem("userdata"));
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: "不可以空数据提交!"
      })
        .then(({ value }) => {
          if (value === userdata.menuTwo) {
          } else {
            this.$message({
              type: "error",
              message: "密码错误"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    // 删除
    deleWarn(row) {
      var userdata = JSON.parse(localStorage.getItem("userdata"));
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: "不可以空数据提交!"
      })
        .then(({ value }) => {
          if (value === userdata.menuTwo) {
            this.$confirm("确定删除吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "error"
            })
              .then(() => {
                let data = {
                  id: row.id
                };
                deleteWarn(data).then(res => {
                  if (res.code == 200) {
                    this.$message.success(res.msg);
                    localStorage.setItem("warnPage", this.pageparm.currentPage);
                    location.reload();
                  } else {
                    this.$message.error(res.msg);
                  }
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除"
                });
              });
          } else {
            this.$message({
              type: "error",
              message: "密码错误"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    // 类型
    Type: function(row) {
      if (row.type == 0) {
        return "用户创建";
      } else if (row.type == 1) {
        return "桩主创建";
      } else if (row.type == 2) {
        return "充电桩自主上传";
      }
    },
    // 处理状态
    Status: function(row) {
      if (row.status == 0) {
        return "未处理";
      } else if (row.status == 1) {
        return "已处理";
      }
    },
    // 充电桩厂家类型
    formatFactoryType(row) {
      if (row.factoryType == 0) {
        return "科士达";
      } else if (row.factoryType == 1) {
        return "星星充电";
      } else if (row.factoryType == 2) {
        return "公牛";
      }
    },
    // 重置数据
    chongzhi() {
      this.stationName = "";
      this.reason = "";
      this.userName = "";
      this.status = "";
      this.timestamp = "";
      this.startTime = "";
      this.getdata(1);
    },
    // 搜索数据
    search() {
      if (this.startTime != "") {
        this.timestamp = Math.floor(new Date(this.startTime).getTime() / 1000);
      }
      this.getdata(1);
    },
    // 获取数据
    getdata(page) {
      this.loading = true;
      var parameter = {
        page: (page - 1) * 20,
        stationName: this.stationName,
        reason: this.reason,
        userName: this.userName,
        status: this.status,
        startTime: this.timestamp
      };
      getWarnList(parameter).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          this.warnData = res.data.list;
          this.pageparm.currentPage = page;
          this.pageparm.total = res.data.count;
          return;
        }
      });
    }
  }
};
</script>

<style></style>
